package org.example.controller;


import org.example.controller.request.TrafficPageRequest;
import org.example.controller.request.UseTrafficRequest;
import org.example.service.TrafficService;
import org.example.util.JsonData;
import org.example.vo.TrafficVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 谢超
 * @since 2023-07-16
 */
@RestController
@RequestMapping("/api/traffic/v1")
public class TrafficController {

    @Resource
    private TrafficService trafficService;

    @Value("${rpc.token}")
    private String rpcToken;

    /**
     * 使用流量包API（这个接口用feign接口调用）
     * @param useTrafficRequest
     * @param request
     * @return
     */
    @PostMapping("reduce")
    public JsonData useTraffic(@RequestBody UseTrafficRequest useTrafficRequest, HttpServletRequest request) {

        String requestHeader = request.getHeader("rpc-token");
        if (rpcToken.equalsIgnoreCase(requestHeader)) {
            // 具体使用流量包
            JsonData jsonData = trafficService.reduce(useTrafficRequest);
            return jsonData;
        } else {
            return JsonData.buildError("非法请求");
        }
    }

    /**
     * 分页查看可用的流量包
     * @param request
     * @return
     */
    @PostMapping("page")
    public JsonData pageAvailable(@RequestBody TrafficPageRequest request){
        Map<String, Object> map = trafficService.pageAvailable(request);

        return JsonData.buildSuccess(map);
    }

    @GetMapping("detail/{trafficId}")
    public JsonData detail(@PathVariable("trafficId") long trafficId) {
        TrafficVO trafficVO = trafficService.detail(trafficId);
        return JsonData.buildSuccess(trafficVO);
    }
}

